package com.chat.simplechat.service;

import com.chat.simplechat.entity.LoginUser;
import com.chat.simplechat.exception.BeanException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户信息全局存储
 * @author wangyabin
 * @date 2022/11/1 16:36
 */
@Service
public class UserInfoService {
    
    private static String[] headPortraits = new String[]{
      "https://img2.woyaogexing.com/2022/10/03/93cb1c8fd392a02f!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/03/ab8e0e592cb04f90!400x400.png",
      "https://img2.woyaogexing.com/2022/10/03/7e556fd0f9994d1d!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/4511cfaa173939df!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/a48a2cc0a25c025d!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/c4da4bddcad8da82!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/3cafef31068a8b71!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/8bb0c6e83688eb3c!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/1e24ce14b6328d96!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/01/936e67d41457e783!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/02/29108f944bc7e2c1!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/29/b789b32cead4e3b7!400x400.jpg",
      "https://img2.woyaogexing.com/2022/10/29/b789b32cead4e3b7!400x400.jpg"      
    };
    private final Map<String,LoginUser> loginUsers = new HashMap<>();
    
    public void registerBean(String username,LoginUser loginUser){
        Random random = new Random();
        int i = random.nextInt(headPortraits.length);
        String headPortrait = headPortraits[i];
        loginUser.setHeadPortrait(headPortrait);
        loginUsers.put(username,loginUser);
    }
    
    public LoginUser getLoginUser(String username){
        LoginUser user = loginUsers.get(username);
        if(!Optional.ofNullable(user).isPresent()){
            throw new BeanException("No bean named '" + username + "' is defined");
        }
        return user;
    }
}
